package com.nativetalk.controller.app.four.course;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.book.TdNtBookCourse;
import com.nativetalk.bean.comment.TdNtCommentCouse;
import com.nativetalk.bean.course.TdNtCoursePictureList;
import com.nativetalk.bean.course.TwoTsNtCourseInfoDetail;
import com.nativetalk.bean.course.catalog.TdNtCourseCatalog;
import com.nativetalk.bean.level.TdNtCourseLevelDetail;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.course.TdNtMembCourseDetail;
import com.nativetalk.bean.setmeal.TsNtSetmealIndex;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.Lang;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.service.member.course.search.MembCourseSearchService;
import com.nativetalk.service.three.book.search.ThreeBookSearchService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangzheng on 2017/2/10.
 */
@Controller
public class FourCourseController {
    private static Logger logger = Logger.getLogger(FourCourseController.class);

    @Resource
    private MembCourseSearchService membCourseSearchService;
    @Resource
    private ThreeBookSearchService threeBookSearchService;

    /**
     * @return RetInfo
     * @Purpose 教材信息
     * @version 4.1
     * @time 2017-02-10
     * @author wangzheng
     */
    @RequestMapping(value = "/app/11/course/index", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo index(@RequestBody Map<String, String> mapParam, @RequestHeader(value = "token", required = false) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(mapParam));


            Map<String, Object> map = new HashMap<>();
            Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);
            map.put("free", tsNtWebSiteConfIndexMap.get("9").getData_value());
            map.put("free_start", tsNtWebSiteConfIndexMap.get("10").getData_value());
            map.put("free_end", tsNtWebSiteConfIndexMap.get("11").getData_value());
            map.put("share", tsNtWebSiteConfIndexMap.get("12").getData_value());
            map.put("share_name", tsNtWebSiteConfIndexMap.get("13").getData_value());
            map.put("share_url", tsNtWebSiteConfIndexMap.get("14").getData_value());
            map.put("share_picutre", tsNtWebSiteConfIndexMap.get("15").getData_value());
            map.put("share_content", tsNtWebSiteConfIndexMap.get("16").getData_value());

            Map<String, TwoTsNtCourseInfoDetail> tsNtCourseInfoDetailMapTwo = (Map<String, TwoTsNtCourseInfoDetail>) MemcachedUtils.get(MemcachedKey.tsNtCourseInfoDetailMapTwo);
            map.put("course", tsNtCourseInfoDetailMapTwo.get(mapParam.get("cou_id")));
            Map<String, List<TdNtCommentCouse>> tdNtCommentCouseMap = (Map<String, List<TdNtCommentCouse>>) MemcachedUtils.get(MemcachedKey.tdNtCommentCouseMap);

            Map<String, Map<String, List<TdNtCourseCatalog>>> tdNtCourseCatalogLevelMap = (Map<String, Map<String, List<TdNtCourseCatalog>>>) MemcachedUtils.get(MemcachedKey.tdNtCourseCatalogLevelMap);
            map.put("level", tdNtCourseCatalogLevelMap.get(mapParam.get("cou_id")));
            Map<String, List<TdNtCourseLevelDetail>> tdNtCourseLevelDetailsMap = (Map<String, List<TdNtCourseLevelDetail>>) MemcachedUtils.get(MemcachedKey.tdNtCourseLevelDetailsMap);
            map.put("levelDetail", tdNtCourseLevelDetailsMap.get(mapParam.get("cou_id")));

            /**
             * 查找前十条评论
             */
            List<TdNtCommentCouse> tdNtCommentCouses = tdNtCommentCouseMap.get(mapParam.get("cou_id"));
            int totalRecord;
            if (tdNtCommentCouses != null) {
                totalRecord = tdNtCommentCouses.size();//总条数
            } else {
                totalRecord = 0;//总条数
            }

            int totalPage;//总页数
            int pageSize = 10;
            int currentPage = 1;

            if (totalRecord % pageSize == 0) {
                totalPage = totalRecord / pageSize;
            } else {
                totalPage = (totalRecord / pageSize) + 1;
            }
            if (currentPage >= totalPage) {
                currentPage = totalPage;
            }
            if (tdNtCommentCouses == null) {
                map.put("comment", tdNtCommentCouses);
            } else if (tdNtCommentCouses.size() > 10) {
                map.put("comment", tdNtCommentCouses.subList(0, 10));
            } else {
                map.put("comment", tdNtCommentCouses);
            }
            map.put("currentPage", currentPage);
            map.put("totalPage", totalPage);
            map.put("totalRecord", totalRecord);


            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = MemcachedUtils.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }


            Map<String, List<TdNtCoursePictureList>> tdNtCoursePictureListMap = (Map<String, List<TdNtCoursePictureList>>) MemcachedUtils.get(MemcachedKey.tdNtCoursePictureListMap);
            List<TdNtCoursePictureList> coursePictureLists = tdNtCoursePictureListMap.get(mapParam.get("cou_id"));
            if (o != null) {

                if (!TdNtMember.class.isInstance(o)) {
                    RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                    logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                    return retInfo;
                }

                TdNtMember tdNtMember = (TdNtMember) o;
                TdNtMembCourseDetail tdNtMembCourse = membCourseSearchService.findTdNtMembCourseDetail(tdNtMember.getMemb_id(), Integer.valueOf(mapParam.get("cou_id")));
                if (tdNtMembCourse != null) {
                    map.put("studySize", tdNtMembCourse.getStudy_page());
                    map.put("coursePictureSize", coursePictureLists.size());
                } else {
                    map.put("studySize", 0);
                    map.put("coursePictureSize", coursePictureLists.size());
                }
                map.put("share_url", tsNtWebSiteConfIndexMap.get("14").getData_value() + "?invite_code=" + tdNtMember.getMemb_invite_code());

                /**
                 * 查找用户是否购买套餐,及是否有该课程课程表
                 */
                TdNtBookCourse tdNtBookCourse = new TdNtBookCourse();
                tdNtBookCourse.setCou_id(Integer.valueOf(mapParam.get("cou_id")));
                tdNtBookCourse.setMemb_id(tdNtMember.getMemb_id());
                TdNtBookCourse bookCourse = threeBookSearchService.findBook(tdNtBookCourse);
                if (bookCourse != null) {
                    Map<String, Object> book = new HashMap<>();
                    book.put("book_cou_id", bookCourse.getBook_cou_id());
                    book.put("state", bookCourse.getState());
                    map.put("book_course", book);
                }
            } else {
                map.put("studySize", 0);
                map.put("coursePictureSize", coursePictureLists.size());
            }
            if (coursePictureLists.size() >= 5) {
                map.put("coursePicture", coursePictureLists.subList(0, 5));
            } else {
                map.put("coursePicture", coursePictureLists);
            }

            RetInfo retInfo = new RetInfo();
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取教程数据成功");
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @return RetInfo
     * @Purpose 课程套餐信息
     * @version 4.1
     * @time 2017-02-13
     * @author wangzheng
     */
    @RequestMapping(value = "/app/11/course/set/choose", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo chooseSet(@RequestBody Map<String, String> mapParam) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(mapParam));

            RetInfo retInfo = new RetInfo();
            String cou_id = mapParam.get("cou_id");//cou_id
            List<TsNtSetmealIndex> tsNtSetmealIndexs = membCourseSearchService.findSetmealByCouId(cou_id);
            if (tsNtSetmealIndexs == null) {
                tsNtSetmealIndexs = new ArrayList<>();
            }

            Map<String, Object> map = new HashMap<>();
            map.put("setmeals", tsNtSetmealIndexs);
            map.put("cou_id", cou_id);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取课程套餐数据成功");
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @return RetInfo
     * @Purpose 选定课程套餐
     * @version 4.1
     * @time 2017-02-14
     * @author wangzheng
     */
    @RequestMapping(value = "/app/11/course/set/confirm", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo confirmSet(@RequestBody Map<String, String> mapParam) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(mapParam));

            RetInfo retInfo = new RetInfo();
            Map<String, Object> map = new HashMap<>();
            String setId = mapParam.get("set_id");
            Map<String, TsNtSetmealIndex> tsNtSetmealAllIndexMap = (Map<String, TsNtSetmealIndex>) MemcachedUtils.get(MemcachedKey.tsNtSetmealAllIndexMap);
            TsNtSetmealIndex tsNtSetmealIndex = tsNtSetmealAllIndexMap.get(setId);
            map.put(setId, tsNtSetmealIndex);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取课程套餐数据成功");
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }
}
